<template>
    <div class="page-wrap" v-loading="loading">
        <div class="page-cont">
            <div style="margin-bottom: 8px">
                <a-input-search allowClear style="min-width: 200px" placeholder="请输入版本号" enter-button @search="handleSearch"> </a-input-search>
            </div>

            <flexbox style="flex: 1; overflow: hidden" align="flex-start" direction="column" justify="space-between">
                <div class="abnormal" :style="{ flex: 1, width: leftWidth }">
                    <a-tabs v-model:activeKey="activeKey" @change="handleTabChange" class="fixed-tabs">
                        <a-tab-pane key="1" tab="版本树"> </a-tab-pane>
                        <a-tab-pane key="2" tab="游离预发布版本"> </a-tab-pane>
                        <a-tab-pane key="3" tab="测试版本"> </a-tab-pane>
                    </a-tabs>

                    <div class="tab-content">
                        <div v-if="activeKey === '1'">
                            <flexbox class="tab-cont" justify="center" v-if="isTreeEmpty">
                                <a-empty></a-empty>
                            </flexbox>
                            <a-tree
                                class="tab-cont"
                                :tree-data="treeData"
                                :replaceFields="{ children: 'subNodes', key: 'id', title: 'versionNumber' }"
                                :autoExpandParent="autoExpandParent"
                                v-model:selectedKeys="selectedKeys"
                                v-model:expandedKeys="expandedKeys"
                                @select="handleSelectTreeNode"
                                v-else
                            >
                                <template v-slot:title="{ versionNumber, pmpProductDetailDTO, type }">
                                    <flexbox class="title-wrap">
                                        <div v-if="versionNumber.indexOf(searchValue) > -1">
                                            {{ versionNumber.substr(0, versionNumber.indexOf(searchValue)) }}
                                            <span style="color: #f50">{{ searchValue }}</span>
                                            {{ versionNumber.substr(versionNumber.indexOf(searchValue) + searchValue.length) }}
                                        </div>
                                        <span v-else>{{ versionNumber }}</span>
                                        <!-- 必须是么有子产品的产品，必须是预发布版本，必须不是统一发版 -->
                                        <div v-if="systemInfo.catalogType === '1' && type === '3' && pmpProductDetailDTO && !isUnifyRelease">
                                            <span style="margin: 0 2px">-</span>
                                            <span>{{ pmpProductDetailDTO.systemName }}</span>
                                        </div>
                                    </flexbox>
                                </template>
                            </a-tree>
                        </div>
                        <div v-else-if="activeKey === '2'">
                            <div style="position: relative; height: 100%; overflow: hidden">
                                <flexbox justify="center" class="tab-cont" v-if="isFlatEmpty">
                                    <a-empty></a-empty>
                                </flexbox>
                                <div class="tab-cont" style="padding-left: 8px" v-else>
                                    <div v-for="item of flatList" :key="item.id">
                                        <flexbox
                                            style="width: calc(100% - 6px); overflow-x: hidden; text-overflow: ellipsis; white-space: nowrap"
                                            :class="[selectedVersion.id === item.id ? 'activeted-color' : '', 'title-wrap', 'flat-item-wrap']"
                                            @click="handleSelectVersion(item)"
                                        >
                                            <a-tooltip :title="item.versionNumber">
                                                <span v-if="item.jiraVersionId" style="color: #b3b6bb"> {{ item.versionNumber }}</span>
                                                <span v-else> {{ item.versionNumber }}</span>
                                            </a-tooltip>
                                        </flexbox>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-else-if="activeKey === '3'">
                            <flexbox justify="center" class="tab-cont" v-if="isTestFlatEmpty">
                                <a-empty></a-empty>
                            </flexbox>
                            <div class="tab-cont" style="padding-left: 8px" v-else>
                                <div v-for="item of testFlatList" :key="item.id">
                                    <flexbox
                                        style="width: calc(100% - 6px); overflow-x: hidden; text-overflow: ellipsis; white-space: nowrap"
                                        :class="[selectedVersion.id === item.id ? 'activeted-color' : '', 'title-wrap', 'flat-item-wrap']"
                                        @click="handleSelectVersion(item)"
                                    >
                                        <a-tooltip :title="item.versionNumber">
                                            <span> {{ item.versionNumber }}</span>
                                        </a-tooltip>
                                    </flexbox>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <flexbox direction="column" align="flex-start" class="margin-t-12" v-if="activeKey !== '3'">
                    <flexbox justify="center" v-if="showAddBtn">
                        <a-button style="width: 100%" type="primary" size="mini" @click="handleCreate">新建版本</a-button>
                    </flexbox>
                    <flexbox
                        v-if="
                            systemDetail.id &&
                            !disabled &&
                            systemInfo.catalogType !== '2' &&
                            systemInfo.subNodes.length &&
                            systemDetail.isOutsideSystem === '0'
                        "
                        style="margin-top: 12px"
                    >
                        <a-checkbox :checked="isUnifyRelease" @change="handleCheckReleaseChange">是否统一发版</a-checkbox>
                        <a-tooltip title="提示：启用统一发版的含义是子产品在新建预发布版本时共用产品级的版本号，版本号在产品层级进行管理；">
                            <QuestionCircleOutlined />
                        </a-tooltip>
                    </flexbox>
                </flexbox>
            </flexbox>
        </div>
        <CreateVersionModal ref="createModalRef" @success="handleCreateSuccess" />
    </div>
</template>

<script lang="ts">
import api from '@/api';
import store from '@/store';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue/es';
import { transformToList, getParentKey } from '@/utils/tree';
import CreateVersionModal from './CreateVersionModal.vue';
import { QuestionCircleOutlined } from '@ant-design/icons-vue';
import { defineComponent, reactive, toRefs, ref, unref, watch, computed } from 'vue';
export default defineComponent({
    name: 'dicTree',
    components: {
        CreateVersionModal,
        QuestionCircleOutlined
    },
    props: {
        systemInfo: {
            type: Object,
            default: () => ({})
        },
        proSystemInfo: {
            type: Object,
            default: () => ({})
        },
        systemDetail: {
            type: Object,
            default: () => ({})
        },
        disabled: {
            type: Boolean,
            default: false
        },
        leftWidth: {
            type: String,
            default: ''
        }
    },
    emits: ['select', 'tabChange', 'checkReleaseChange'],
    setup(props, { emit }) {
        const router = useRouter();
        const route = useRoute();
        const createModalRef = ref<any>();
        const state = reactive<any>({
            treeData: [],
            flatList: [],
            testFlatList: [],
            expandedKeys: [],
            autoExpandParent: false,
            searchValue: '',
            loading: false,
            isTreeEmpty: false,
            isFlatEmpty: false,
            isTestFlatEmpty: false,
            activeKey: '1',
            selectedVersion: {},
            selectedKeys: [],
            isUnifyRelease: false
        });
        const showAddBtn = computed(() => {
            // 子产品且统一发版
            const res = props.systemInfo.catalogType == 2 && state.isUnifyRelease;
            return !props.disabled && !res && props.systemDetail.isOutsideSystem === '0';
        });
        const transformDataByFlatProperty = (data, fields = { keyField: 'node', childrenField: 'subNodes' }) => {
            const { keyField, childrenField } = fields;
            data.forEach((item, index) => {
                data[index] = {
                    ...data[index],
                    ...data[index][keyField]
                };
                if (item[childrenField] && item[childrenField].length) {
                    data[index][childrenField] = transformDataByFlatProperty(item[childrenField], fields);
                } else {
                    data[index][childrenField] = null;
                }
            });
            return data;
        };
        const getFlatList = async (versionNumber = null) => {
            state.flatList = [];
            state.isFlatEmpty = false;
            const query = {
                versionNumber,
                catalogCode: props.systemInfo.catalogCode,
                type: 3
            };
            const { success, moule } = await api.versionControlModel.getFreeVersions(query);
            if (success) {
                if (moule && moule.length) {
                    state.flatList = [...moule];
                } else {
                    state.isFlatEmpty = true;
                }
            } else {
                state.isFlatEmpty = true;
            }
            return success;
        };
        const getTestFlatList = async (versionNumber = null) => {
            state.testFlatList = [];
            state.isTestFlatEmpty = false;
            const query = {
                versionNumber,
                catalogCode: props.systemInfo.catalogCode,
                type: 4
            };
            const { success, moule } = await api.versionControlModel.getFreeVersions(query);
            if (success) {
                if (moule && moule.length) {
                    state.testFlatList = [...moule];
                } else {
                    state.isTestFlatEmpty = true;
                }
            } else {
                state.isTestFlatEmpty = true;
            }
            return success;
        };
        const getTreeList = async () => {
            state.isTreeEmpty = false;
            const query = {
                catalogCode: props.systemInfo.catalogCode
            };
            let { success, moule } = await api.versionControlModel.getVersionTree(query);
            if (success) {
                moule = JSON.parse(moule);
                if (moule && moule.length) {
                    state.treeData = [...transformDataByFlatProperty(moule)];
                    store.commit('versionControl/SET_VERSIONTREEDATA', state.treeData);
                    state.selectedVersion = {
                        ...state.treeData[0].node
                    };
                    console.log('tree', state.treeData);
                    state.selectedKeys = [state.selectedVersion.id];
                    emit('select', state.selectedVersion);
                } else {
                    state.selectedVersion = {};
                    state.treeData = [];
                    state.isTreeEmpty = true;
                    state.selectedKeys = [];
                    store.commit('versionControl/SET_VERSIONTREEDATA', []);
                }
            } else {
                state.isTreeEmpty = true;
                state.selectedVersion = {};
                state.selectedKeys = [];
            }
            return success;
        };
        const getList = async () => {
            state.loading = true;
            await getTreeList();
            await getFlatList();
            await getTestFlatList();
            state.loading = false;
            emit('tabChange');
        };
        const handleCreate = () => {
            unref(createModalRef).open({
                systemInfo: props.systemInfo,
                proSystemInfo: props.proSystemInfo,
                isUnifyRelease: state.isUnifyRelease
            });
        };

        const handleSelectTreeNode = (val, { node }) => {
            state.selectedVersion = {
                ...node.dataRef
            };
            emit('select', state.selectedVersion);
        };
        const handleSelectVersion = (item) => {
            state.selectedVersion = item;
            emit('select', state.selectedVersion);
        };
        const handleCheckReleaseChange = async (val) => {
            state.isUnifyRelease = val.target.checked;
            const query = {
                ...props.systemDetail,
                isUnifyRelease: state.isUnifyRelease ? '1' : '0'
            };
            const { success, errorMsg } = await api.productDetailModel.save(query);
            if (success) {
                getTreeList();
                // 需要通知更新系统详情，因为系统详情里的是否统一发版会影响后续的判断
                emit('checkReleaseChange');
                message.success('设置成功');
            } else {
                message.error(errorMsg);
            }
        };
        const handleCreateSuccess = () => {
            // 创建完毕之后跳转到创建预发布版本页面
            if (route.query.catalogCode && route.query.catalogType) {
                router.back();
            }
            getList();
        };
        const handleTabChange = () => {
            state.selectedVersion = {};
            state.selectedKeys = [];
            emit('select', state.selectedVersion);
            emit('tabChange');
        };
        const handleSearch = (val) => {
            if (state.activeKey === '1') {
                const dataList = transformToList(state.treeData, {
                    keyField: 'id',
                    titleField: 'versionNumber',
                    childrenField: 'subNodes'
                });
                const expandedKeys = dataList
                    .map((item: any) => {
                        if (item.versionNumber.indexOf(val) > -1) {
                            return getParentKey(item.id, state.treeData, {
                                keyField: 'id',
                                childrenField: 'subNodes'
                            });
                        }
                        return null;
                    })
                    .filter((item, i, self) => item && self.indexOf(item) === i);
                state.searchValue = val;
                state.expandedKeys = expandedKeys;
                state.autoExpandParent = true;
            } else if (state.activeKey === '2') {
                getFlatList(val);
            } else {
                getTestFlatList(val);
            }
        };
        getList();

        watch(
            () => props.systemInfo,
            () => {
                getList();
            },
            { deep: true }
        );
        watch(
            () => props.systemDetail,
            (n) => {
                state.isUnifyRelease = n.isUnifyRelease === '1' ? true : false;
            },
            { deep: true }
        );
        return {
            ...toRefs(state),
            createModalRef,
            showAddBtn,
            handleSearch,
            getList,
            handleCreate,
            handleSelectTreeNode,
            handleSelectVersion,
            handleCheckReleaseChange,
            handleCreateSuccess,
            handleTabChange
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    height: 100%;
    position: relative;
    .page-cont {
        height: 100%;
        display: flex;
        flex-direction: column;
        .title-wrap {
            .icon-cont {
                display: none;
                .anticon {
                    margin-left: 8px;
                }
            }
            &:hover {
                .icon-cont {
                    display: block;
                }
            }
        }
        .flat-item-wrap {
            display: inline-block;
            height: 24px;
            margin: 0;
            padding: 0 5px;
            color: #30445e;
            line-height: 24px;
            text-decoration: none;
            vertical-align: top;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 12px;
            &:hover {
                background-color: #edeff3;
            }
        }
        .activeted-color {
            background-color: #a3e2ff !important;
        }

        .abnormal {
            overflow: hidden;
            overflow-y: auto;
            position: relative;
            ::v-deep(.ant-tabs-tabpane) {
                box-sizing: border-box;
                overflow-y: auto;
            }

            ::v-deep(.fixed-tabs) {
                .ant-tabs-bar {
                    position: fixed;
                    z-index: 100; /* 确保头部在最上层 */
                    background: #fff;
                }
            }
            .tab-content {
                margin-top: 48px; /* 与头部的高度相同 */
            }
        }
        ::v-deep(.ant-input-affix-wrapper) {
            height: 32px !important;
        }

        .tab-cont {
            height: 100%;
            // margin-bottom: 18px !important;
            overflow-x: hidden;
            overflow: auto;
            scrollbar-width: none;
        }
    }
}
</style>